package cc.kdniao.api;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class printOrder
 */
@WebServlet("/printOrder")
public class printOrder extends HttpServlet {
    private static final long serialVersionUID = 1L;
    //用户ID，快递鸟提供，注意保管，不要泄漏
    final String EBusinessID="1886744";//即用户ID，登录快递鸟官网会员中心获取 https://www.kdniao.com/UserCenter/v4/UserHome.aspx
    //API key，快递鸟提供，注意保管，不要泄漏
    final String ApiKey="3d157635-8263-41d4-a715-43da668a762d";//即API key，登录快递鸟官网会员中心获取 https://www.kdniao.com/UserCenter/v4/UserHome.aspx
    final Integer IsPreview = 0; //是否预览 0-不预览 1-预览

    /**
     * @see HttpServlet#HttpServlet()
     */
    public printOrder() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //response.getWriter().append("Served at: ").append(request.getContextPath());
        PrintWriter print = response.getWriter();
        String jsonResult = "";
        try {
            String ip = getIpAddress(request);
            jsonResult = getPrintParam(ip);
        } catch (Exception e) {
            //write log
        }
        print.println(jsonResult);
        print.flush();
        print.close();
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, UnsupportedEncodingException {
        // TODO Auto-generated method stub
        response.setContentType("");
        PrintWriter print = response.getWriter();
        String jsonResult = "";
        try {
            String ip = getIpAddress(request);
            jsonResult = getPrintParam(ip);
        } catch (Exception e) {
            //wirte log
        }
        print.println(jsonResult);
        print.flush();
        print.close();
    }

    /**
     * get print order param to json string
     * @return
     * 
     * @throws Exception 
     */
    private String getPrintParam(String ip) throws Exception {
        String data = "[{\"OrderCode\":\"012652618308\",\"PortName\":\"SF\"},{\"OrderCode\":\"012652618308\",\"PortName\":\"打印机名称二\"}]";
		String result = "{\"RequestData\": \"" + URLEncoder.encode(data, "UTF-8")
				+ "\", \"EBusinessID\":\"" + "1886744" + "\", \"DataSign\":\""
				+ encrpy(/* ip + */ data, ApiKey) + "\", \"IsPreview\":\""
                        + IsPreview + "\"}";
        return result;
    }

    private String md5(String str, String charset) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes(charset));
        byte[] result = md.digest();
        StringBuffer sb = new StringBuffer(32);
        for (int i = 0; i < result.length; i++) {
            int val = result[i] & 0xff;
            if (val <= 0xf) {
                sb.append("0");
            }
            sb.append(Integer.toHexString(val));
        }
        return sb.toString().toLowerCase();
    }

    private String encrpy(String content, String key) throws UnsupportedEncodingException, Exception {
        String charset = "UTF-8";
        ApiKdniaoService api = new ApiKdniaoService();
        return new String(api.base64Encode(md5(content + key, charset).getBytes(charset)));
    }

    /** 
     * 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址; 
     *  
     * @param request 
     * @return 
     * @throws IOException 
     */
    public final static String getIpAddress(HttpServletRequest request) throws IOException {
        // 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址  

        String ip = request.getHeader("X-Forwarded-For");

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } else if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++) {
                String strIp = (String) ips[index];
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }
		if(innerIP(ip)){
			ip=getV4IP();
		}
        return ip;
    }
	public static boolean innerIP(String ip) {
        if (ip.equals("0:0:0:0:0:0:0:1")) {
            return true;
        }
        String pattern = "((192\\.168|172\\.([1][6-9]|[2]\\d|3[01]))" + "(\\.([2][0-4]\\d|[2][5][0-5]|[01]?\\d?\\d)){2}|" + "^(\\D)*10(\\.([2][0-4]\\d|[2][5][0-5]|[01]?\\d?\\d)){3})";

        Pattern reg = Pattern.compile(pattern);
        Matcher match = reg.matcher(ip);

        return match.find();

    }
	public static String getV4IP() {
        String ip = "";
        String chinaz = "https://www.kdniao.com/External/GetIp.ashx";

        String inputLine = "";
        String read = "";
        try {
            URL url = new URL(chinaz);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            while ((read = in.readLine()) != null) {
                inputLine += read;
            }
            ip=inputLine;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ip;
    }
}
